package com.rabbitmq.demo.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQTopicExchangeConsumer {
    private static String host = "127.0.0.1";
    private static String userName = "guest";
    private static String passWord = "guest";
    private static int port = 5672;
    private static final  String ExchangeName = "topicOne";
    private static String routingKey = "#.error";
    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            //1、连接到RabbitMQ服务器
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setPort(port);
            factory.setUsername(userName);
            factory.setPassword(passWord);
            Connection connect = factory.newConnection();
            Channel channel = connect.createChannel();
            // 2、声明name为ExchangeName的topic模式交换器
            channel.exchangeDeclare(ExchangeName, "topic");
            // 3、声明随机队列绑定到交换机，并获取路由与routingKey匹配的消息,随机队列在消费者断开连接后自动删除
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, ExchangeName, routingKey);
            //4、消费消息
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println(routingKey + "|接收消息 => " + message);
                }
            };
            channel.basicConsume(queueName, true, consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
